/* ====================================================================
 * (#)Header: JmsReceiverTest.java
 * (#)Revision: 
 * (#)Date Created: 02-Nov-09 10:32:15 AM
 * (#)Created By: Karol Wozniak
 * ====================================================================
 *
 * Copyright (c) 2007 karolak .  All rights reserved.
 *
 * ====================================================================
 * 
 * The software application represented here is the sole property of 
 * karolak. Its unauthorized utilization is expressly prohibited.
 * 
 * ====================================================================
 */
package com.karolak.jms;

import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * <code>JmsReceiverTest</code> is used to ....
 * 
 * @author <a href="mailto:kwozniak@hotmail.com">Karol Wozniak</a>
 */
public class JmsReceiverIT {

	private static JmsReceiver receiver;

	@BeforeClass
	public static void init() throws Exception {
		String destinationJndiName = "queue/ForumChannel";
		receiver = new JmsReceiver(destinationJndiName);
		receiver.start();
	}

	@AfterClass
	public static void destroy() throws Exception {
		receiver.close();
	}

	@Test
	public void testReceive() throws Exception {
		boolean continiue = true;
		while (continiue) {
			Message message = receiver.receiveMessage();
			continiue = onMessage(message);
		}
	}

	public boolean onMessage(Message message) {
		if (message instanceof TextMessage) {
			return onTextMessage((TextMessage) message);
		} else if (message instanceof ObjectMessage) {
			return onObjectMessage((ObjectMessage) message);
		} else {
			System.out.println(this + "  received message: " + message);
		}
		return true;
	}

	protected boolean onTextMessage(TextMessage message) {
		try {
			if ("exit".equals(message.getText())) {
				return false;
			}
			System.out.println(this + "  received TextMessage: " + message.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	protected boolean onObjectMessage(ObjectMessage message) {
		try {
			System.out.println(this + "  received ObjectMessage: " + message);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}
